package com.reds.backend.service.impl.homeArticle;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reds.backend.pojo.Article;
import com.reds.backend.pojo.Homearticle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.reds.backend.service.homeArticle.homeArticleCRUDService;
import com.reds.backend.mapper.homearticleMapper;
import com.reds.backend.mapper.articleMapper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class homeArticleCRUDServiceImpl implements homeArticleCRUDService{
    @Autowired
    homearticleMapper homearticleMapper;
    @Autowired
    articleMapper articleMapper;
    @Override
    public String updataShowHome(int id,int aid) {
        QueryWrapper<Homearticle>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Homearticle homearticle = homearticleMapper.selectOne(queryWrapper);
        homearticle.setAid(aid);
        homearticleMapper.updateById(homearticle);
        return "success";
    }

    @Override
    public String deteleShowHome(int id) {
        homearticleMapper.deleteById(id);
        return "success";
    }

    @Override
    public JSONObject getShowHomeByTag(String tag) {
        System.out.println(tag);
        class withHome {
            public int id;
            public int hid;
            public String title;
            public String face;
            public String author;
            public Date time;
            public String content;
        }
        QueryWrapper<Homearticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag",tag).orderByDesc("id");
        List<Homearticle> list = homearticleMapper.selectList(queryWrapper);
        List<withHome> articles = new ArrayList<>();
        for(Homearticle homearticle :list){
            Article article = articleMapper.selectById(homearticle.getAid());
            if(article == null ) continue;
            withHome withHome = new withHome();
            withHome.id = article.getId();
            withHome.hid = homearticle.getId();
            withHome.face=article.getFace();
            withHome.title=article.getTitle();
            withHome.author=article.getAuthor();
            withHome.time=article.getTime();
            withHome.content = article.getContent();
            articles.add(withHome);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("article",articles);
        return jsonObject;
    }
}
